<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>打字机效果(css+js)</title>
    <style>
      #output {
        /*  设置字体为等宽字体 */
        font-family: 'Courier New', Courier, monospace;
        /* 保留空格和换行符 */
        white-space: pre;
        /* 模拟光印 */
        border-right: 2px solid;
        display: inline-block;
        animation: blink 0.75s step-end infinite;
      }

      @keyframes blink {
        50% {
          /* 使其消失又出现 */
          border-color: transparent;
        }
      }
    </style>
  </head>
  <body>
    <div id="output"></div>
    <hr>
    <button id="againButton">再来一次</button>

    <script>
      const text = '欢迎来到打字机效果演示！hello world';
      let index = 0;

      function type() {
        if (index < text.length) {
          document.getElementById('output').innerHTML += text.charAt(index);
          index++;
          setTimeout(type, 500); // 控制打字速度
        }
      }

      type();

      function again() {
        index = 0;
        document.getElementById('output').innerHTML = '';
        type();
      }

      // 添加事件监听器
      // 不是在vue文件，不能使用@click
      document.getElementById('againButton').addEventListener('click', again);
    </script>
  </body>
</html>
